package com.st.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.st.domain.*;
import com.st.po.RiskQuestionAnswerPo;
import com.st.po.WeChatPayPo;
import com.st.po.WeChatPayRequest;
import com.st.service.*;
import com.st.util.WXPayUtil;
import com.st.util.WeChatPayUtil;
import com.st.util.WxLoginUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @version V 1.0
 * @auther ROG
 * @date 2024/10/24
 * @project_name back
 * @description
 */
@RestController
@RequestMapping("app")
public class AppController  extends BaseController {
    @Autowired
    private IStTeachersService stTeachersService;
    @Autowired
    private IStCoursesService stCoursesService;
    @Autowired
    private IStCourseCategoriesService stCourseCategoriesService;
    @Autowired
    private IStPurchaseRecordsService stPurchaseRecordsService;
    @Autowired
    private IStCourseChaptersService stCourseChaptersService;
    @Autowired
    private IStStudyRecordsService stStudyRecordsService;
    @Autowired
    private IStRiskAssessmentQuestionsService stRiskAssessmentQuestionsService;

    @Autowired
    private WeChatPayUtil weChatPayUtil;

    @Autowired
    private WxLoginUtils wxLoginUtils;

    @Autowired
    private IStUsersService stUsersService;


    /*
    1.老师列表，返回2个数据，
     */
    @GetMapping("/teacher/list")
    public AjaxResult list(StTeachers stTeachers)
    {
        List<StTeachers> list = stTeachersService.selectStTeachersList(stTeachers);
        if(list != null && list.size() != 0){
            return success(list);
        }else{
            return error("暂无数据");
        }
    }

    /*
    2.课程列表，按分类，不分页，
     */
    @GetMapping("/course/list")
    public AjaxResult list(StCourses stCourses)
    {
        List<StCourses> list = stCoursesService.selectStCoursesList(stCourses);
        if(list != null && list.size() != 0){
            return success(list);
        }else{
            return error("暂无数据");
        }
    }

    /*
    3.返回课程分类列表
     */
    @GetMapping("/course/category/list")
    public AjaxResult list(StCourseCategories stCourseCategories)
    {
        List<StCourseCategories> list = stCourseCategoriesService.selectStCourseCategoriesList(stCourseCategories);
        if(list != null && list.size() != 0){
            return success(list);
        }else{
            return error("暂无数据");
        }
    }

    /*
    4.根据老师编号获取他的详情，+ 他的课程列表
     */
    @GetMapping(value = "/teacher/info")
    public AjaxResult getInfo(@RequestParam("tid") Integer id)
    {
        HashMap<String,Object> map = new HashMap<String,Object>();
        StTeachers stTeachers = stTeachersService.selectStTeachersById(id);

        QueryWrapper<StCourses> qw = new QueryWrapper<>();
        qw.eq("teacher_id",id);

        List<StCourses> coursesList = stCoursesService.list(qw);

        map.put("teacherInfo",stTeachers);
        map.put("coursesList",coursesList);

        return success(map);
    }

    /*
    5.获取当前用户购买的课程记录
     */
    @GetMapping("/record/list")
    public AjaxResult list(StPurchaseRecords stPurchaseRecords)
    {
        List<StPurchaseRecords> list = stPurchaseRecordsService.selectStPurchaseRecordsList(stPurchaseRecords);
        list.stream().forEach(r ->{
            Integer courseId = r.getCourseId();
            StCourses stCourses = stCoursesService.getById(courseId);
            r.setCourseImg(stCourses.getCoverImageUrl());
        });
        if(list != null && list.size() != 0){
            return success(list);
        }else{
            return error("暂无数据");
        }
    }

    /*
    6.根据课程编号获取课程章节列表（章节信息：章节标题+章节时长+章节该学生的学习状态）
        总学习人数、该学生的课程总进度
     */
    @GetMapping("/user/study/list")
    public AjaxResult list(@RequestParam("userId") Integer userId,
                           @RequestParam("courseId") Integer courseId)
    {
        QueryWrapper<StCourseChapters> qw1 = new QueryWrapper<>();
        qw1.eq("course_id",courseId);
        List<StCourseChapters> courseChapters = stCourseChaptersService.list(qw1);  //章节列表

        //查询当前用户对该课程的学习记录信息
        QueryWrapper<StStudyRecords> qw2 = new QueryWrapper<>();
        qw2.eq("user_id",userId);
        List<StStudyRecords> stStudyRecords = stStudyRecordsService.list(qw2);  //学习记录列表

        //整理数据
        courseChapters.stream().forEach(cc -> {
            List<StStudyRecords> collect = stStudyRecords.stream().filter(ssr -> {
                return ssr.getChapterId() == cc.getId();
            }).collect(Collectors.toList());

            cc.setStudyStatus(collect.get(0).getStudyStatus());
        });

        StCourses stCourses = stCoursesService.selectStCoursesById(courseId);  //课程信息


        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("courseChapters",courseChapters);
        map.put("coursesInfo",stCourses);
        return success(map);
    }

    /*
    7.变更章节学习状态
     */
    @GetMapping("update/study")
    public AjaxResult updateStudyRecord(StStudyRecords studyRecords){

        int i = stStudyRecordsService.updateStStudyRecords1(studyRecords);

        return success();
    }


    /*
    8.返回风险测试列表（根据分线评估类型返回）
     */
    @GetMapping("/riskQuestions/list")
    public AjaxResult list(StRiskAssessmentQuestions stRiskAssessmentQuestions)
    {
        List<StRiskAssessmentQuestions> list = stRiskAssessmentQuestionsService.selectStRiskAssessmentQuestionsList(stRiskAssessmentQuestions);
        //转换格式
        List<HashMap<String, Object>> mapList = list.stream().map(rq -> {
            HashMap<String, Object> map = new HashMap<String, Object>();
            map.put("id", rq.getId());
            map.put("title", rq.getQuestion());
            map.put("type", rq.getQuestionType());
            map.put("answer", rq.getCorrectAnswer());
            map.put("userAnswer", null);
            //组建选项集合
            ArrayList<HashMap<String, String>> answerList = new ArrayList<HashMap<String, String>>();
            if (rq.getOptionA() != null && !"".equals(rq.getOptionA())) {
                HashMap<String, String> optionAMap = new HashMap<>();
                optionAMap.put("value", "A");
                optionAMap.put("label", rq.getOptionA());
                answerList.add(optionAMap);
            }
            if (rq.getOptionB() != null && !"".equals(rq.getOptionB())) {
                HashMap<String, String> optionBMap = new HashMap<>();
                optionBMap.put("value", "B");
                optionBMap.put("label", rq.getOptionB());
                answerList.add(optionBMap);
            }
            if (rq.getOptionC() != null && !"".equals(rq.getOptionC())) {
                HashMap<String, String> optionCMap = new HashMap<>();
                optionCMap.put("value", "C");
                optionCMap.put("label", rq.getOptionC());
                answerList.add(optionCMap);
            }
            if (rq.getOptionD() != null && !"".equals(rq.getOptionD())) {
                HashMap<String, String> optionDMap = new HashMap<>();
                optionDMap.put("value", "D");
                optionDMap.put("label", rq.getOptionD());
                answerList.add(optionDMap);
            }
            map.put("answerList", answerList);
            map.put("example", rq.getExplanation());
            return map;
        }).collect(Collectors.toList());


        if(mapList != null && mapList.size() != 0){
            return success(mapList);
        }else{
            return error("暂无数据");
        }
    }


    /*
    9.接收用户答案接口
     */
    @PostMapping("riskQuestions/check")
    public AjaxResult checkQuestionAnswer(@RequestBody List<RiskQuestionAnswerPo> riskQuestionAnswerPoList){
        //遍历判断并组装成绩和最终提示信息
        int score = 0;
        String str1 = "";
        String str2 = "";
        String str3 = "";
        String riskResult = "";

        for(RiskQuestionAnswerPo rqp : riskQuestionAnswerPoList){
            Integer questionId = rqp.getId();
            StRiskAssessmentQuestions questions = stRiskAssessmentQuestionsService.getById(questionId);
            String userAnswerStr = "";
            if(rqp.getUserAnswer() != null && rqp.getUserAnswer().size() > 0){
                List<String> userAnswer = rqp.getUserAnswer();
                userAnswerStr = String.join(",", userAnswer);
            }
            if (questions.getCorrectAnswer().equals(userAnswerStr)){
                //加分
                score += questions.getScore();
            }else{
                //组装提示信息
                str1 += questions.getRiskWarning() + ";";
                str2 += questions.getRiskAnalysis() + ";";
                str3 += questions.getPreventionAdvice() + ";";
            }
        }

        //根据总分得出最终结果
        if(score >= 95){
            riskResult = "低风险";
        }else if(score >= 80){
            riskResult = "中风险";
        }else if(score >= 60){
            riskResult = "高风险";
        }else{
            riskResult = "超高风险";
        }

        HashMap<String,Object> map = new HashMap<String,Object>();
        map.put("score",score);
        map.put("riskResult",riskResult);
        map.put("riskWarning",str1);
        map.put("riskAnalysis",str2);
        map.put("preventionAdvice",str3);

        return success(map);
    }


    /*
    微信小程序支付发起
     */
    @PostMapping("/wx/createOrder")
    public AjaxResult createOrder(@RequestBody WeChatPayPo weChatPayPo) {
        //查询课程信息
        StCourses stCourses = stCoursesService.selectStCoursesById(weChatPayPo.getCourseId());
        String courseName = stCourses.getCourseName();
        BigDecimal price = stCourses.getPrice();
        int priceInt = (int)(price.doubleValue() * 100);
        String courseInfo = "一个名为" + courseName + "的课程";

        //生成订单号
        String orderNumber = "D" + System.currentTimeMillis();

        //查询用户OpenId
        String openId = weChatPayPo.getOpenId();

        WeChatPayRequest paRequest = new WeChatPayRequest(courseInfo,orderNumber,priceInt, weChatPayPo.getSpbillCreateIp(), openId);


        try {
            // 调用微信支付服务生成支付订单
            Map<String, String> result = weChatPayUtil.createOrder(paRequest);

            //1.新增购买记录
            StPurchaseRecords stPurchaseRecords = new StPurchaseRecords();
            stPurchaseRecords.setInternalOrderNo(orderNumber);
            stPurchaseRecords.setPrice(price);
            stPurchaseRecords.setOrderTime(new Date());
            stPurchaseRecords.setOrderStatus(0);
            stPurchaseRecords.setCourseId(stCourses.getId());
            stPurchaseRecords.setCourseName(stCourses.getCourseName());
            stPurchaseRecords.setUserId(weChatPayPo.getUserId());

            stPurchaseRecordsService.insertStPurchaseRecords(stPurchaseRecords);


            //2.给用户课程学习记录表中插入对应数据
            //2.1获取该课程所有章节信息
            QueryWrapper<StCourseChapters> qw = new QueryWrapper<>();
            qw.eq("course_id",stCourses.getId());
            List<StCourseChapters> stCourseChaptersList = stCourseChaptersService.list(qw);

            //2.2循环插入
            for (StCourseChapters stCourseChapters : stCourseChaptersList) {
                StStudyRecords stStudyRecords = new StStudyRecords();
                stStudyRecords.setStudyStatus(0);
                stStudyRecords.setUserId(weChatPayPo.getUserId());
                stStudyRecords.setCourseId(weChatPayPo.getCourseId());
                stStudyRecords.setChapterId(stCourseChapters.getId());

                stStudyRecordsService.insertStStudyRecords(stStudyRecords);
            }

            return AjaxResult.success(result);
        } catch (Exception e) {
            return AjaxResult.error("微信下单失败！" + e.getMessage());
        }
    }


    /*
    微信支付成功的回调函数
     */
    @PostMapping("/wx/notify")
    public String payNotify(HttpServletRequest request) {
        try {
            // 读取微信支付的通知请求体
            BufferedReader reader = request.getReader();
            StringBuilder inputString = new StringBuilder();
            String line;
            while ((line = reader.readLine()) != null) {
                inputString.append(line);
            }
            reader.close();

            // 将 XML 转为 Map
            Map<String, String> resultMap = WXPayUtil.xmlToMap(inputString.toString());

            // 签名验证
            if (WXPayUtil.isSignatureValid(resultMap, "your_api_key")) {
                if ("SUCCESS".equals(resultMap.get("return_code")) && "SUCCESS".equals(resultMap.get("result_code"))) {
                    // 支付成功，处理订单逻辑
                    String outTradeNo = resultMap.get("out_trade_no");  // 商户订单号
                    String transactionId = resultMap.get("transaction_id"); // 微信支付订单号

                    // 这里更新订单状态为已支付，并记录交易号等信息
                    // updateOrderStatus(outTradeNo, transactionId);
                    // 1.修改课程购买记录信息
                    QueryWrapper<StPurchaseRecords> qw = new QueryWrapper<>();
                    qw.eq("internal_order_no",outTradeNo);
                    StPurchaseRecords stPurchaseRecords = stPurchaseRecordsService.getOne(qw);

                    stPurchaseRecords.setOrderStatus(1);
                    stPurchaseRecords.setPaymentTime(new Date());

                    stPurchaseRecordsService.updateStPurchaseRecords(stPurchaseRecords);


                    // 通知微信回调接收成功
                    return "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
                } else {
                    // 支付失败，记录错误信息
                    // handlePaymentFailure(resultMap);
                    return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Payment failure]]></return_msg></xml>";
                }
            } else {
                // 签名验证失败
                return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[Signature Error]]></return_msg></xml>";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[System Error]]></return_msg></xml>";
        }
    }


    @PostMapping(value = "/wx/login",produces = MediaType.APPLICATION_JSON_VALUE)
    public AjaxResult login(@RequestBody Map<String, String> data) {
        String code = data.get("code");
        Map<String, Object> sessionInfo = wxLoginUtils.getSessionInfo(code);

        AjaxResult result = new AjaxResult();
        if (sessionInfo != null && sessionInfo.containsKey("openid")) {
            Object openid = sessionInfo.get("openid");
            QueryWrapper<StUsers> qw = new QueryWrapper<>();
            qw.eq("open_id",openid.toString());
            StUsers users = stUsersService.getOne(qw);
            if(users == null){
                //将微信信息存库
                StUsers user = new StUsers();
                user.setAge(0);
                user.setGender(1);
                user.setNickname("");
                user.setUserStatus(0);
                user.setFirstLoginCode(data.get("code"));
                user.setAvatarUrl("");
                user.setOpenId(openid.toString());
                user.setTotalSpent(BigDecimal.ZERO);
                user.setVipFlag(0);
                user.setWechatAvatarUrl("");
                stUsersService.insertStUsers(user);
            }

            HashMap<String,Object> map = new HashMap<String,Object>();
            map.put("users",users);
            map.put("sessionInfo",sessionInfo);


            result = AjaxResult.success(map);

        } else {
            result = AjaxResult.warn("微信登录失败");
        }
        return result;
    }

}
